package logic

import (
	"backend/apps/book/models"
	"context"
	"database/sql"
	"github.com/pkg/errors"
	"time"

	"backend/apps/book/proto"
	"backend/apps/book/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAuthorLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateAuthorLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAuthorLogic {
	return &UpdateAuthorLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// UpdateAuthor 更新作者信息
func (l *UpdateAuthorLogic) UpdateAuthor(in *proto.Author) (*proto.CommonResponse, error) {
	_, err := l.svcCtx.AuthorModel.FindOne(l.ctx, in.Id)
	if err != nil {
		if errors.Is(err, models.ErrNotFound) {
			return nil, errors.New("作者信息不存在")
		}
		return nil, err
	}

	err = l.svcCtx.AuthorModel.Update(l.ctx, &models.Author{
		Id:        in.Id,
		Name:      in.Name,
		AvatarUrl: in.AvatarUrl,
		Introduction: sql.NullString{
			String: in.Introduction,
			Valid:  true,
		},
		UpdateTime: time.Now().Unix(),
	})
	return &proto.CommonResponse{}, err
}
